import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_index_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_store_detail_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/smart_home_terminal_list_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

///智能家居门店正在使用的终端页面
class SmartHomeUsingTerminalPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "SmartHomeUsingTerminalPage";
  final SmartHomeIndexListItemBean itemBean;

  const SmartHomeUsingTerminalPage({Key key, this.itemBean}):super(key: key);

  @override
  _SmartHomeUsingTerminalPageState createState() => _SmartHomeUsingTerminalPageState();

  ///跳转方法
  static Future<String> navigatorPush(
      BuildContext context, SmartHomeIndexListItemBean itemBean) {
    return RouterUtils.routeForFutureResult(
      context, SmartHomeUsingTerminalPage(
      itemBean: itemBean,
    ),
      routeName: SmartHomeUsingTerminalPage.ROUTER,
    );
  }
}

class _SmartHomeUsingTerminalPageState extends BaseState<SmartHomeUsingTerminalPage>{
  SmartHomeStoreDetailViewModel _viewModel;
  List<TerInfoBean> data;
  @override
  void initState() {
    super.initState();
    _viewModel = SmartHomeStoreDetailViewModel(this);
    _viewModel.getTerminalList(widget?.itemBean?.shid, "", justUsing: true);
    data = new List();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          resizeToAvoidBottomPadding: false,
          resizeToAvoidBottomInset: false,
          backgroundColor: Color(0xFFF6F7F9),
          body: CommonPackUpKeyboardWidget(
            child: Column(
              children: <Widget>[
                _toTopBarWidget(),
                Expanded(
                  child: _toPlaceHolderWidget(),
                ),
              ],
            ),
          ),
        )
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      centerWidget: _toCenterWidget(),
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      backgroundColor: Color(0XFFF6F7F9),
    );
  }

  Widget _toCenterWidget(){
    return Container(
      height: 44,
      alignment: Alignment.center,
      child: Column(
        children: [
          Text(
            widget?.itemBean?.getTitle(),
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.w600,
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          Text(
            widget?.itemBean?.getTerInfo(),
            style: TextStyle(
              fontSize: 10,
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            ),
          ),
        ],
      ),
    );
  }


  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            emptyStatus: value == PlaceHolderStatusType.empty,
            emptyCustomWidget: _defaultEmptyCustomWidget("暂无内容"),
            errorCustomWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
            errorOnClick: () => _viewModel.getTerminalList(widget?.itemBean?.shid, "", justUsing: true),
            loadingOnClick: () => _viewModel.getTerminalList(widget?.itemBean?.shid, "", justUsing: true),
            child: child,
          );
        },
        child: _toBodyWidget());
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toBodyWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.terminalListValueNotifier,
        builder: (BuildContext context, TerminalListDataBean detailBean, Widget child){
          if(detailBean != null && detailBean.terInfo != null){
            data.clear();
            data.addAll(detailBean.terInfo);
          }
          return _toListWidget();
        }
    );
  }

  ///图片展示栏
  Widget _toListWidget(){
    return ListView.separated(
      padding: EdgeInsets.only(top: 0, bottom: 50),
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return _toListItemWidget(context, index,);
      },
      separatorBuilder: (BuildContext context, int index){
        return SizedBox();
      },
      itemCount: data?.length??0,
    );
  }

  ///item
  Widget _toListItemWidget(BuildContext context, int index, ){
    TerInfoBean itemBean = data?.elementAt(index);
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: ()  {
        setState(() {
          if("01" == itemBean?.terflg){
            itemBean?.terflg = "00";
          }else{
            itemBean?.terflg = "01";
          }
        });
      },
      child: Container(
        height: 87,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        alignment: Alignment.centerLeft,
        color: Colors.white,
        child:  _toContentWidget(index, itemBean),
      ),
    );
  }

  Widget _toContentWidget(int index, TerInfoBean itemBean) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Row(
          children: [
            Visibility(
              visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
              child: Text(
                // "硬件ID：",
                "",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  fontSize: 15,
                  // fontWeight: FontWeight.w600
                ),
              ),
            ),
            Expanded(
              child: Text(
                itemBean?.getTerminalName(index),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                  fontSize: 15,
                  // fontWeight: FontWeight.w600
                ),
              ),
            ),
            Spacer(),
            Visibility(
              child: Container(
                alignment: Alignment.centerRight,
                width: 60,
                child: Text(
                  (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())?"已关机":"开机状态",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: (itemBean.onOff == null || itemBean.onOff !=1 || itemBean.getTerminalIsOff())
                        ?Color(0xFF8B93A5)
                        :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                    fontSize: 12,
                  ),
                ),
              ),
            ),
          ],
        ),
        SizedBox(
          height: 4,
        ),
        Container(
          width: 236,
          child: Text(
            showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Color(0xFF8B93A5),
              fontSize: 12,
            ),
          ),
        ),
        SizedBox(
          height: 4,
        ),
        Text(
          "管理员：${itemBean?.manager ?? "-"}${_getLoginStr(itemBean?.loginName) ?? ""}",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: Color(0xFF8B93A5),
            fontSize: 12,
          ),
        )
      ],
    );
  }

  String _getLoginStr(String loginName) {
    if (loginName == null || loginName == "") {
      return null;
    }
    return "（$loginName账号登录）";
  }

}